package com.powernode.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.powernode.entity.Goods;
import com.powernode.entity.Orders;
import com.powernode.mapper.OrdersMapper;
import com.powernode.service.GoodsService;
import com.powernode.service.OrderService;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class OrderServiceImpl extends ServiceImpl<OrdersMapper, Orders> implements OrderService {
    @Resource
    private GoodsService goodsService;
    @Override
    @Transactional
    public int doOrder(Orders orders) {
        //1.查询商品库存
        Goods goods = goodsService.getById(orders.getGoodsId());
        //2.判断库存是否充足
        if (goods.getStore()<=0){
            throw new RuntimeException("库存不足,商品id："+ orders.getGoodsId());
        }
        //减库存
        UpdateWrapper<Goods> updateWrapper = new UpdateWrapper<>();
        updateWrapper.setSql("store=store-1");
        updateWrapper.eq("id",orders.getGoodsId());
        boolean updateResult = goodsService.update(updateWrapper);
        //3.向订单添加数据
        boolean saveResult = save(orders);
        return updateResult && saveResult ? 1 : 0;
    }
}
